package cn.edu.nju.ws.sview.wyge.servlets;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import cn.edu.nju.ws.sview.cache.RelationCache;
import cn.edu.nju.ws.sview.views.Group;
import cn.edu.nju.ws.sview.wyge.relations.adataset.relations.Relation;
import cn.edu.nju.ws.sview.wyge.relations.adataset.relations.Relations;

/**
 * Servlet implementation class Entity
 */
public class SaveRelation extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SaveRelation() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String json = null;
		response.setCharacterEncoding("utf-8");
		JSONObject result = new JSONObject();
//		if(request.getSession().getAttribute("gid") != null){
//			String group = Group.getGroupNameById(Integer.valueOf((String)request.getSession().getAttribute("gid")));
			if (request.getParameter("data") != null) {
				System.out.println("in SaveRelation:"+"\t:"+request.getParameter("data"));
				json = request.getParameter("data");
				String str = URLDecoder.decode(json, "UTF-8");
				JSONObject regtJSON = (JSONObject) JSONValue.parse(str);
				int id = Integer.parseInt((String) regtJSON.get("id"));
				String name = (String) regtJSON.get("name");
				String user = (String) regtJSON.get("user");
//				String group = Group.getGroupNameById(Integer.valueOf((String) regtJSON.get("gid")));
				String group = (String)request.getSession().getAttribute("groupName");
				
				Relation rel = (Relation) request.getSession().getAttribute(
						"relation" + id);
				if(rel == null){
					result.put("result", "nosession");
					System.err.println("****Error in SaveRelation.java! rel=null");
				}else{
					rel.setName(name);
	//				rel.setUser(user);
					rel.setGroup(group);
					rel.serialize();//===========
	
					result.put("result", "OK");
					result.put("rel_id", rel.getRelationID());
				}
				response.getWriter().print(result);
				System.out.println("continue========="+rel.getRelationID());
				RelationCache.getInstance().refreshAvailable(rel.getRelationID());//================
				
			}else if(request.getParameter("info") != null){
				System.out.println("in SaveRelation:"+"\t:"+request.getParameter("info"));
				json = request.getParameter("info");
				String str = URLDecoder.decode(json, "UTF-8");
				JSONObject regtJSON = (JSONObject) JSONValue.parse(str);
				int id = Integer.parseInt((String) regtJSON.get("id"));
				String name = (String) regtJSON.get("name");
				String user = (String) regtJSON.get("user");
				
				int ds_id = Integer.valueOf((String)regtJSON.get("ds_id"));
				String ds_type = (String)regtJSON.get("ds_type");
//				String group = Group.getGroupNameById(Integer.valueOf((String) regtJSON.get("gid")));
				String group = (String)request.getSession().getAttribute("groupName");
				if(group==null){
					result.put("result", "nogroup");
					response.getWriter().print(result);
					return;
				}
				Relation rel = (Relation) request.getSession().getAttribute(
						"relation" + id);
				if(rel == null){
					result.put("result", "nosession");
					System.err.println("****Error in SaveRelation.java! rel=null");
				}else{
					rel.setName(name);
	//				rel.setUser(user);
					rel.setGroup(group);
					rel.serialize();
					request.getSession().removeAttribute("relation"+id);
					request.getSession().setAttribute("relation"+rel.getRelationID(), rel);
					result.put("result", "OK");
					int relation_id = rel.getRelationID();
					result.put("rel_id", relation_id);
					
					//add favorite
					if(Relations.isTrash(ds_type, ds_id, user, relation_id)){
						Relations.delTrash(ds_type, ds_id, user, relation_id);
					}
					Relations.addFavorite(ds_type, ds_id, user, relation_id);
				}
				response.getWriter().print(result);
				System.out.println("continue========="+rel.getRelationID());
				RelationCache.getInstance().refreshAvailable(rel.getRelationID());//================
			}
//		}else{
//			result.put("result", "nogid");
//			response.getWriter().print(result);
//		}
	}
}
